{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !wget https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\n",
    "# !unzip uncased_L-12_H-768_A-12.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:87: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import bert\n",
    "from bert import run_classifier\n",
    "from bert import optimization\n",
    "from bert import tokenization\n",
    "from bert import modeling\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import pandas as pd\n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "with open('dataset.json') as fopen:\n",
    "    data = json.load(fopen)\n",
    "    \n",
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "BERT_VOCAB = 'uncased_L-12_H-768_A-12/vocab.txt'\n",
    "BERT_INIT_CHKPNT = 'uncased_L-12_H-768_A-12/bert_model.ckpt'\n",
    "BERT_CONFIG = 'uncased_L-12_H-768_A-12/bert_config.json'\n",
    "\n",
    "tokenizer = tokenization.FullTokenizer(\n",
    "      vocab_file=BERT_VOCAB, do_lower_case=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import youtokentome as yttm\n",
    "\n",
    "bpe = yttm.BPE(model='bpe.model')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from unidecode import unidecode\n",
    "from tqdm import tqdm\n",
    "\n",
    "def get_inputs(x, y):\n",
    "    input_ids, input_masks, segment_ids, ys = [], [], [], []\n",
    "    for i in tqdm(range(len(x))):\n",
    "        tokens_a = tokenizer.tokenize(unidecode(x[i]))\n",
    "        tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n",
    "        \n",
    "        segment_id = [0] * len(tokens)\n",
    "        input_id = tokenizer.convert_tokens_to_ids(tokens)\n",
    "        input_mask = [1] * len(input_id)\n",
    "\n",
    "        input_ids.append(input_id)\n",
    "        input_masks.append(input_mask)\n",
    "        segment_ids.append(segment_id)\n",
    "        \n",
    "        r = bpe.encode(y[i], output_type=yttm.OutputType.ID) + [EOS]\n",
    "        if len([k for k in r if k == 0]):\n",
    "            print(y[i], i)\n",
    "            break\n",
    "        \n",
    "        ys.append(r)\n",
    "        \n",
    "    return input_ids, input_masks, segment_ids, ys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 200000/200000 [01:24<00:00, 2359.12it/s]\n"
     ]
    }
   ],
   "source": [
    "train_input_ids, train_input_masks, train_segment_ids, train_Y = get_inputs(train_X, train_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5000/5000 [00:01<00:00, 2711.31it/s]\n"
     ]
    }
   ],
   "source": [
    "test_input_ids, test_input_masks, test_segment_ids, test_Y = get_inputs(test_X, test_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "bert_config = modeling.BertConfig.from_json_file(BERT_CONFIG)\n",
    "epoch = 20\n",
    "batch_size = 16\n",
    "warmup_proportion = 0.1\n",
    "num_train_steps = len(train_input_ids)\n",
    "num_warmup_steps = int(num_train_steps * warmup_proportion)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "30522"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bert_config.vocab_size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "BASE_PARAMS = defaultdict(\n",
    "    lambda: None,  # Set default value to None.\n",
    "\n",
    "    # Input params\n",
    "    default_batch_size=2048,  # Maximum number of tokens per batch of examples.\n",
    "    default_batch_size_tpu=32768,\n",
    "    max_length=256,  # Maximum number of tokens per example.\n",
    "\n",
    "    # Model params\n",
    "    initializer_gain=1.0,  # Used in trainable variable initialization.\n",
    "    vocab_size=32000,  # Number of tokens defined in the vocabulary file.\n",
    "    hidden_size=768,  # Model dimension in the hidden layers.\n",
    "    num_hidden_layers=6,  # Number of layers in the encoder and decoder stacks.\n",
    "    num_heads=8,  # Number of heads to use in multi-headed attention.\n",
    "    filter_size=2048,  # Inner layer dimension in the feedforward network.\n",
    "\n",
    "    # Dropout values (only used when training)\n",
    "    layer_postprocess_dropout=0.1,\n",
    "    attention_dropout=0.1,\n",
    "    relu_dropout=0.1,\n",
    "\n",
    "    # Training params\n",
    "    label_smoothing=0.1,\n",
    "    learning_rate=1.0,\n",
    "    learning_rate_decay_rate=1.0,\n",
    "    learning_rate_warmup_steps=16000,\n",
    "\n",
    "    # Optimizer params\n",
    "    optimizer_adam_beta1=0.9,\n",
    "    optimizer_adam_beta2=0.997,\n",
    "    optimizer_adam_epsilon=1e-09,\n",
    "\n",
    "    # Default prediction params\n",
    "    extra_decode_length=50,\n",
    "    beam_size=4,\n",
    "    alpha=0.6,  # used to calculate length normalization in beam search\n",
    "\n",
    "    # TPU specific parameters\n",
    "    use_tpu=False,\n",
    "    static_batch=False,\n",
    "    allow_ffn_pad=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformer import model_utils\n",
    "from transformer import utils\n",
    "from transformer.transformer import DecoderStack\n",
    "from transformer import beam_search\n",
    "from transformer import embedding_layer\n",
    "\n",
    "class Model:\n",
    "    def __init__(\n",
    "        self,\n",
    "        learning_rate = 2e-5,\n",
    "        training = True,\n",
    "    ):\n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.segment_ids = tf.placeholder(tf.int32, [None, None])\n",
    "        self.input_masks = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        model = modeling.BertModel(\n",
    "            config=bert_config,\n",
    "            is_training=training,\n",
    "            input_ids=self.X,\n",
    "            input_mask=self.input_masks,\n",
    "            token_type_ids=self.segment_ids,\n",
    "            use_one_hot_embeddings=False)\n",
    "        \n",
    "        self.decoder_stack = DecoderStack(BASE_PARAMS, training)\n",
    "        attention_bias = model_utils.get_padding_bias(self.X)\n",
    "        \n",
    "        output_layer = model.get_sequence_output()\n",
    "        \n",
    "        self.embedding_softmax_layer = embedding_layer.EmbeddingSharedWeights(\n",
    "        BASE_PARAMS[\"vocab_size\"], BASE_PARAMS[\"hidden_size\"], 'gather')\n",
    "        \n",
    "        with tf.name_scope(\"decode\"):\n",
    "            decoder_inputs = self.embedding_softmax_layer(self.Y)\n",
    "            with tf.name_scope(\"shift_targets\"):\n",
    "                decoder_inputs = tf.pad(\n",
    "                    decoder_inputs, [[0, 0], [1, 0], [0, 0]])[:, :-1, :]\n",
    "            with tf.name_scope(\"add_pos_encoding\"):\n",
    "                length = tf.shape(decoder_inputs)[1]\n",
    "                decoder_inputs += model_utils.get_position_encoding(\n",
    "                    length, BASE_PARAMS[\"hidden_size\"])\n",
    "            if training:\n",
    "                decoder_inputs = tf.nn.dropout(\n",
    "                    decoder_inputs, 1 - BASE_PARAMS[\"layer_postprocess_dropout\"])\n",
    "            decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias(length)\n",
    "            outputs = self.decoder_stack(\n",
    "              decoder_inputs, output_layer, decoder_self_attention_bias,\n",
    "              attention_bias)\n",
    "            self.training_logits = self.embedding_softmax_layer.linear(outputs)\n",
    "                \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        \n",
    "        self.optimizer = optimization.create_optimizer(self.cost, learning_rate, \n",
    "                                                       num_train_steps, num_warmup_steps, False)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        def _get_symbols_to_logits_fn(max_decode_length):\n",
    "            timing_signal = model_utils.get_position_encoding(\n",
    "                max_decode_length + 1, BASE_PARAMS[\"hidden_size\"])\n",
    "            decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias(\n",
    "                max_decode_length)\n",
    "            def symbols_to_logits_fn(ids, i, cache):\n",
    "                decoder_input = ids[:, -1:]\n",
    "                decoder_input = self.embedding_softmax_layer(decoder_input)\n",
    "                decoder_input += timing_signal[i:i + 1]\n",
    "                self_attention_bias = decoder_self_attention_bias[:, :, i:i + 1, :i + 1]\n",
    "                decoder_outputs = self.decoder_stack(\n",
    "                  decoder_input, cache.get(\"encoder_outputs\"), self_attention_bias,\n",
    "                  cache.get(\"encoder_decoder_attention_bias\"), cache)\n",
    "                logits = self.embedding_softmax_layer.linear(decoder_outputs)\n",
    "                logits = tf.squeeze(logits, axis=[1])\n",
    "                return logits, cache\n",
    "            return symbols_to_logits_fn\n",
    "        \n",
    "        batch_size = tf.shape(output_layer)[0]\n",
    "        input_length = tf.shape(output_layer)[1]\n",
    "        max_decode_length = input_length + BASE_PARAMS[\"extra_decode_length\"]\n",
    "        symbols_to_logits_fn = _get_symbols_to_logits_fn(max_decode_length)\n",
    "        initial_ids = tf.zeros([batch_size], dtype=tf.int32)\n",
    "        cache = {\n",
    "        \"layer_%d\" % layer: {\n",
    "            \"k\": tf.zeros([batch_size, 0, BASE_PARAMS[\"hidden_size\"]]),\n",
    "            \"v\": tf.zeros([batch_size, 0, BASE_PARAMS[\"hidden_size\"]]),\n",
    "        } for layer in range(BASE_PARAMS[\"num_hidden_layers\"])}\n",
    "        cache[\"encoder_outputs\"] = output_layer\n",
    "        cache[\"encoder_decoder_attention_bias\"] = attention_bias\n",
    "        \n",
    "        decoded_ids, scores = beam_search.sequence_beam_search(\n",
    "            symbols_to_logits_fn=symbols_to_logits_fn,\n",
    "            initial_ids=initial_ids,\n",
    "            initial_cache=cache,\n",
    "            vocab_size=32000,\n",
    "            beam_size=1,\n",
    "            alpha=BASE_PARAMS[\"alpha\"],\n",
    "            max_decode_length=max_decode_length,\n",
    "            eos_id=EOS)\n",
    "        \n",
    "        top_decoded_ids = decoded_ids[:, 0, 1:]\n",
    "        self.fast_result = top_decoded_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:171: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:409: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:490: The name tf.assert_less_equal is deprecated. Please use tf.compat.v1.assert_less_equal instead.\n",
      "\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:358: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:671: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).\n",
      "  warnings.warn('An interactive session is already active. This can '\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/translation/transformer/attention_layer.py:39: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/model_utils.py:89: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/embedding_layer.py:48: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/model_utils.py:71: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/autograph/converters/directives.py:119: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:27: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:32: The name tf.train.polynomial_decay is deprecated. Please use tf.compat.v1.train.polynomial_decay instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:70: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/math_grad.py:1375: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/beam_search.py:420: calling reduce_logsumexp_v1 (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "keep_dims is deprecated, use keepdims instead\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Model()\n",
    "\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import re\n",
    "\n",
    "def get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n",
    "    \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\n",
    "    assignment_map = {}\n",
    "    initialized_variable_names = {}\n",
    "\n",
    "    name_to_variable = collections.OrderedDict()\n",
    "    for var in tvars:\n",
    "        name = var.name\n",
    "        m = re.match('^(.*):\\\\d+$', name)\n",
    "        if m is not None:\n",
    "            name = m.group(1)\n",
    "        name_to_variable[name] = var\n",
    "\n",
    "    init_vars = tf.train.list_variables(init_checkpoint)\n",
    "\n",
    "    assignment_map = collections.OrderedDict()\n",
    "    for x in init_vars:\n",
    "        (name, var) = (x[0], x[1])\n",
    "        if 'bert/' + name in name_to_variable:\n",
    "            assignment_map[name] = name_to_variable['bert/' + name]\n",
    "            initialized_variable_names[name] = 1\n",
    "            initialized_variable_names[name + ':0'] = 1\n",
    "        elif name in name_to_variable:\n",
    "            assignment_map[name] = name_to_variable[name]\n",
    "            initialized_variable_names[name] = 1\n",
    "            initialized_variable_names[name + ':0'] = 1\n",
    "        \n",
    "\n",
    "    return (assignment_map, initialized_variable_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "tvars = tf.trainable_variables()\n",
    "\n",
    "checkpoint = BERT_INIT_CHKPNT\n",
    "assignment_map, initialized_variable_names = get_assignment_map_from_checkpoint(tvars, \n",
    "                                                                                checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from uncased_L-12_H-768_A-12/bert_model.ckpt\n"
     ]
    }
   ],
   "source": [
    "saver = tf.train.Saver(var_list = assignment_map)\n",
    "saver.restore(sess, checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "i = 0\n",
    "index = min(i + batch_size, len(train_input_ids))\n",
    "batch_x = train_input_ids[i: index]\n",
    "batch_x = pad_sequences(batch_x, padding='post')\n",
    "batch_mask = train_input_masks[i: index]\n",
    "batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "batch_segment = train_segment_ids[i: index]\n",
    "batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "batch_y = pad_sequences(train_Y[i: index], padding='post')\n",
    "acc, cost, r = sess.run(\n",
    "    [model.accuracy, model.cost, model.fast_result],\n",
    "    feed_dict = {\n",
    "        model.Y: batch_y,\n",
    "        model.X: batch_x,\n",
    "        model.input_masks: batch_mask,\n",
    "        model.segment_ids: batch_segment\n",
    "    },\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [44:21<00:00,  4.70it/s, accuracy=0.155, cost=6.27] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:24<00:00, 12.73it/s, accuracy=0.242, cost=5.41]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 0, training loss: 7.195237, training acc: 0.118680, valid loss: 5.926563, valid acc: 0.200815\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [44:05<00:00,  4.73it/s, accuracy=0.287, cost=4.68]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.47it/s, accuracy=0.333, cost=4.09]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 1, training loss: 5.066592, training acc: 0.272305, valid loss: 4.342011, valid acc: 0.340727\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [44:03<00:00,  4.73it/s, accuracy=0.379, cost=3.82]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.37it/s, accuracy=0.387, cost=3.56]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 2, training loss: 3.880865, training acc: 0.384843, valid loss: 3.586298, valid acc: 0.414048\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [44:00<00:00,  4.73it/s, accuracy=0.428, cost=3.38]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.52it/s, accuracy=0.452, cost=3.08]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 3, training loss: 3.245811, training acc: 0.448329, valid loss: 3.153671, valid acc: 0.458197\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [43:58<00:00,  4.74it/s, accuracy=0.463, cost=3.04]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.55it/s, accuracy=0.473, cost=2.85]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 4, training loss: 2.838538, training acc: 0.492572, valid loss: 2.884781, valid acc: 0.487033\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop:  95%|█████████▌| 11889/12500 [41:49<02:08,  4.76it/s, accuracy=0.554, cost=2.14]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  26%|██▌       | 3252/12500 [11:26<32:15,  4.78it/s, accuracy=0.542, cost=2.42]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  54%|█████▎    | 6693/12500 [23:31<20:48,  4.65it/s, accuracy=0.622, cost=1.97]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  82%|████████▏ | 10299/12500 [36:12<07:45,  4.73it/s, accuracy=0.536, cost=2.29]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop: 100%|██████████| 12500/12500 [43:57<00:00,  4.74it/s, accuracy=0.506, cost=2.58]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.51it/s, accuracy=0.543, cost=2.6] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 6, training loss: 2.345052, training acc: 0.552142, valid loss: 2.589172, valid acc: 0.522635\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop:   8%|▊         | 1023/12500 [03:36<42:16,  4.52it/s, accuracy=0.617, cost=2.14]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  40%|███▉      | 4999/12500 [17:34<25:49,  4.84it/s, accuracy=0.588, cost=2.1] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  71%|███████   | 8848/12500 [31:04<12:28,  4.88it/s, accuracy=0.511, cost=2.29]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop: 100%|██████████| 12500/12500 [43:58<00:00,  4.74it/s, accuracy=0.54, cost=2.46] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.25it/s, accuracy=0.532, cost=2.71]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 7, training loss: 2.185663, training acc: 0.572866, valid loss: 2.514815, valid acc: 0.531109\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop:   1%|▏         | 171/12500 [00:36<42:26,  4.84it/s, accuracy=0.5, cost=2.48]  IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  29%|██▉       | 3613/12500 [12:46<33:33,  4.41it/s, accuracy=0.523, cost=2.32]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  59%|█████▉    | 7369/12500 [26:02<18:58,  4.51it/s, accuracy=0.651, cost=1.7] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  82%|████████▏ | 10205/12500 [36:03<08:28,  4.51it/s, accuracy=0.48, cost=2.83] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  90%|████████▉ | 11225/12500 [39:39<04:29,  4.74it/s, accuracy=0.574, cost=2.07]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:   8%|▊         | 992/12500 [03:30<41:21,  4.64it/s, accuracy=0.561, cost=2.13]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  18%|█▊        | 2235/12500 [07:53<34:54,  4.90it/s, accuracy=0.56, cost=2.34] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  40%|████      | 5048/12500 [17:50<26:03,  4.77it/s, accuracy=0.644, cost=1.74]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  49%|████▊     | 6064/12500 [21:25<23:26,  4.58it/s, accuracy=0.662, cost=1.62]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  69%|██████▊   | 8588/12500 [30:19<14:04,  4.63it/s, accuracy=0.653, cost=1.73]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  78%|███████▊  | 9713/12500 [34:18<10:12,  4.55it/s, accuracy=0.656, cost=1.81]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop: 100%|██████████| 12500/12500 [44:11<00:00,  4.71it/s, accuracy=0.557, cost=2.22]\n",
      "test minibatch loop:  36%|███▋      | 114/313 [00:08<00:14, 13.49it/s, accuracy=0.503, cost=2.59]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:   8%|▊         | 1022/12500 [03:37<40:23,  4.74it/s, accuracy=0.619, cost=1.86]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  35%|███▍      | 4344/12500 [15:23<29:25,  4.62it/s, accuracy=0.589, cost=2.13]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  64%|██████▍   | 7980/12500 [28:14<16:11,  4.65it/s, accuracy=0.693, cost=1.4] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  94%|█████████▍| 11763/12500 [41:39<02:30,  4.89it/s, accuracy=0.648, cost=1.76]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  23%|██▎       | 2849/12500 [10:07<33:30,  4.80it/s, accuracy=0.586, cost=2.04]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  52%|█████▏    | 6459/12500 [22:56<20:19,  4.95it/s, accuracy=0.628, cost=1.86]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  84%|████████▍ | 10488/12500 [37:15<08:39,  3.87it/s, accuracy=0.603, cost=2.17]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop:  12%|█▏        | 1517/12500 [05:23<37:37,  4.87it/s, accuracy=0.57, cost=2.13]  IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  42%|████▏     | 5272/12500 [18:44<24:56,  4.83it/s, accuracy=0.601, cost=1.87] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  71%|███████   | 8831/12500 [31:25<13:21,  4.58it/s, accuracy=0.619, cost=1.81]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop: 100%|██████████| 12500/12500 [44:26<00:00,  4.69it/s, accuracy=0.601, cost=1.98] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.21it/s, accuracy=0.565, cost=2.45]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 12, training loss: 1.757933, training acc: 0.633067, valid loss: 2.367259, valid acc: 0.550553\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [45:11<00:00,  4.61it/s, accuracy=0.566, cost=1.99] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.27it/s, accuracy=0.538, cost=2.39]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 13, training loss: 1.715457, training acc: 0.639882, valid loss: 2.355022, valid acc: 0.552821\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [45:21<00:00,  4.59it/s, accuracy=0.572, cost=2.02] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.34it/s, accuracy=0.554, cost=2.36]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 14, training loss: 1.682720, training acc: 0.645245, valid loss: 2.348547, valid acc: 0.553258\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [44:18<00:00,  4.70it/s, accuracy=0.609, cost=1.97] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.29it/s, accuracy=0.548, cost=2.38]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 15, training loss: 1.661970, training acc: 0.648400, valid loss: 2.345818, valid acc: 0.553272\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop:  60%|█████▉    | 7488/12500 [28:57<18:08,  4.60it/s, accuracy=0.695, cost=1.39]  IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop: 100%|██████████| 12500/12500 [46:43<00:00,  4.46it/s, accuracy=0.609, cost=1.94] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.30it/s, accuracy=0.575, cost=2.43]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 16, training loss: 1.652219, training acc: 0.650080, valid loss: 2.350214, valid acc: 0.552423\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [45:23<00:00,  4.59it/s, accuracy=0.592, cost=1.94]  \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.38it/s, accuracy=0.565, cost=2.39]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 17, training loss: 1.652442, training acc: 0.650099, valid loss: 2.350846, valid acc: 0.552391\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [45:26<00:00,  4.58it/s, accuracy=0.606, cost=1.92] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.35it/s, accuracy=0.565, cost=2.49]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 18, training loss: 1.652238, training acc: 0.649970, valid loss: 2.346917, valid acc: 0.551565\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [44:15<00:00,  4.71it/s, accuracy=0.612, cost=1.93] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:23<00:00, 13.45it/s, accuracy=0.565, cost=2.36]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 19, training loss: 1.651971, training acc: 0.650319, valid loss: 2.348038, valid acc: 0.553802\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "import time\n",
    "\n",
    "for EPOCH in range(epoch):\n",
    "\n",
    "    train_acc, train_loss, test_acc, test_loss = [], [], [], []\n",
    "    pbar = tqdm(\n",
    "        range(0, len(train_input_ids), batch_size), desc = 'train minibatch loop'\n",
    "    )\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_input_ids))\n",
    "        batch_x = train_input_ids[i: index]\n",
    "        batch_x = pad_sequences(batch_x, padding='post')\n",
    "        batch_mask = train_input_masks[i: index]\n",
    "        batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "        batch_segment = train_segment_ids[i: index]\n",
    "        batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i: index], padding='post')\n",
    "        acc, cost, _ = sess.run(\n",
    "            [model.accuracy, model.cost, model.optimizer],\n",
    "            feed_dict = {\n",
    "                model.Y: batch_y,\n",
    "                model.X: batch_x,\n",
    "                model.input_masks: batch_mask,\n",
    "                model.segment_ids: batch_segment\n",
    "            },\n",
    "        )\n",
    "        train_loss.append(cost)\n",
    "        train_acc.append(acc)\n",
    "        pbar.set_postfix(cost = cost, accuracy = acc)\n",
    "        \n",
    "    pbar = tqdm(range(0, len(test_input_ids), batch_size), desc = 'test minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_input_ids))\n",
    "        batch_x = test_input_ids[i: index]\n",
    "        batch_x = pad_sequences(batch_x, padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i: index], padding='post')\n",
    "        batch_mask = test_input_masks[i: index]\n",
    "        batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "        batch_segment = test_segment_ids[i: index]\n",
    "        batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "        acc, cost = sess.run(\n",
    "            [model.accuracy, model.cost],\n",
    "            feed_dict = {\n",
    "                model.Y: batch_y,\n",
    "                model.X: batch_x,\n",
    "                model.input_masks: batch_mask,\n",
    "                model.segment_ids: batch_segment\n",
    "            },\n",
    "        )\n",
    "        test_loss.append(cost)\n",
    "        test_acc.append(acc)\n",
    "        pbar.set_postfix(cost = cost, accuracy = acc)\n",
    "        \n",
    "    train_loss = np.mean(train_loss)\n",
    "    train_acc = np.mean(train_acc)\n",
    "    test_loss = np.mean(test_loss)\n",
    "    test_acc = np.mean(test_acc)\n",
    "    print(\n",
    "        'epoch: %d, training loss: %f, training acc: %f, valid loss: %f, valid acc: %f\\n'\n",
    "        % (EPOCH, train_loss, train_acc, test_loss, test_acc)\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 313/313 [08:32<00:00,  1.64s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = test_input_ids[i: index]\n",
    "    batch_x = pad_sequences(batch_x, padding='post')\n",
    "    batch_y = pad_sequences(test_Y[i: index], padding='post')\n",
    "    batch_mask = test_input_masks[i: index]\n",
    "    batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "    batch_segment = test_segment_ids[i: index]\n",
    "    batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "    feed = {\n",
    "        model.X: batch_x,\n",
    "        model.input_masks: batch_mask,\n",
    "        model.segment_ids: batch_segment\n",
    "    }\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 1 and i not in [101, 102]])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 1 and i not in [101, 102]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.23225775"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
